//
//  UIView+MKUIBadgeProtocol.m
//  MKUI
//
//  Created by moon on 15/10/28.
//  Copyright © 2015年 heimavista. All rights reserved.
//

#import "UIView+MKUIBadgeProtocol.h"
#import <objc/runtime.h>
#import "MKUIBadgeView.h"
@implementation UIView (MKUIBadgeProtocol)
+ (Class)mkBadgeClass{
	return [MKUIBadgeTextView class];
}
#define kUIView_mkBadgeClass "kUIView_mkBadgeClass"
- (Class)mkBadgeClass{
	Class c = objc_getAssociatedObject(self, kUIView_mkBadgeClass);
	return c;
}
- (void)setMkBadgeClass:(Class)mkBadgeClass{
    if(self.mkBadgeClass!=mkBadgeClass){
        [self.mkBadgeView removeFromSuperview];
        self.mkBadgeView = nil;
        objc_setAssociatedObject(self, kUIView_mkBadgeClass, mkBadgeClass, OBJC_ASSOCIATION_ASSIGN);
    }
}
- (UIView<MKUIBadgeProtocol> *)mkBadgeView{
    UIView<MKUIBadgeProtocol> * v = objc_getAssociatedObject(self, "mkBadgeView");
    return v;
}
- (void)setMkBadgeView:(UIView<MKUIBadgeProtocol> * _Nullable)mkBadgeView{
    objc_setAssociatedObject(self, "mkBadgeView", mkBadgeView, OBJC_ASSOCIATION_RETAIN);
}
- (void)mkSetBadge:(nullable NSString *)badge animated:(BOOL)animated{
    if(badge.length==0){
		[self.mkBadgeView setBadge:badge toView:self animated:animated];
	}else{
		UIView<MKUIBadgeProtocol> *view = self.mkBadgeView;
		if(!view){
			Class c = self.mkBadgeClass?:[self.class mkBadgeClass];
			if(c){
				view = [[c alloc] init];
			}
            self.mkBadgeView = view;
		}
		if(view){
			[view setBadge:badge toView:self animated:animated];
		}
	}
}
- (void)mkRefreshBadge{
    [self.mkBadgeView refreshBadge];
}
@end
